/**
 * ===========================================================================
 * 版权所有 湖南免了么网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.mianle.me
 * ===========================================================================
 * 11:33 2018/7/4
 */
package com.mianle.userapi.service;

import java.sql.*;

/**
 * @Author: yiyuan
 * @Description:
 * @Date: Created in 11:33 2018/7/4
 */
public class TestTransaction {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/mydb", "root", "root");
            System.out.println("连接数据库成功!");
            stmt = con.createStatement();
            // JAVA默认为TRUE,我们自己处理需要设置为FALSE,并且修改为手动提交,才可以调用rollback()函数
            con.setAutoCommit(false);
            stmt.addBatch("insert into people values(078,'ding','duo')");
            stmt.addBatch("insert into people values(30,'nokia','ddd')");
            stmt.executeBatch();
            // 事务提交
            con.commit();
            // 设置为自动提交,改为TRUE
            con.setAutoCommit(true);

            /*
             * String sql = "select * from people"; rs = stmt.executeQuery(sql);
             * while(rs.next()){ System.out.println(rs.getString("id") + " " +
             * rs.getString("name")); }
             */
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException se) {
            se.printStackTrace();
            try {
                // 产生的任何SQL异常都需要进行回滚,并设置为系统默认的提交方式,即为TRUE
                if (con != null) {
                    con.rollback();
                    con.setAutoCommit(true);
                }
            } catch (SQLException se1) {
                se.printStackTrace();
            }
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                    rs = null;
                }
                if (stmt != null) {
                    stmt.close();
                    stmt = null;
                }
                if (con != null) {
                    con.close();
                    con = null;
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }

}

